package com.lhf.warnsend.warnsendjson.service.impl;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.lhf.warnsend.warnsendjson.dao.UseAlarmMsgDao;
import com.lhf.warnsend.warnsendjson.entity.UseAlarmMsg;
import com.lhf.warnsend.warnsendjson.message.RequestContent;
import com.lhf.warnsend.warnsendjson.message.SmsProperties;
import com.lhf.warnsend.warnsendjson.message.util.AesCiphertext;
import com.lhf.warnsend.warnsendjson.message.util.MD5Ciphertext;
import com.lhf.warnsend.warnsendjson.service.UseAlarmMsgService;
import com.lhf.warnsend.warnsendjson.vo.MsgBodyVO;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * (UseAlarmMsg)表服务实现类
 *
 * @author liuhf
 * @since 2021-09-02 16:08:43
 */
@Service("useAlarmMsgService")
@EnableConfigurationProperties({SmsProperties.class})
public class UseAlarmMsgServiceImpl implements UseAlarmMsgService {
    private static final Logger logger = LoggerFactory.getLogger(UseAlarmMsgServiceImpl.class);

    @Resource
    private SmsProperties prop;

    @Resource
    private UseAlarmMsgDao useAlarmMsgDao;

    @Scheduled(fixedRateString = "${sms.schedule}")
    public void schedule() {
        Random random = new Random(System.nanoTime());
        List<UseAlarmMsg> msgs = useAlarmMsgDao.findUnSend();
        List<RequestContent.Batch> batchList = msgs.stream().map(msg -> RequestContent.buildBatch().content(msg.getAlarmTitle()).mobile(msg.getTargetData()).templateNo(prop.getTemplateNo())).collect(Collectors.toList());
        RequestContent.RequestHeader requestHeader = RequestContent.buildRequestHeader().channel(prop.getChannel())
                .channelNo(prop.getChannelNo())
                .IdNo(prop.getIdNo())
                .loanType(prop.getLoanType())
                .reqNo("QD" + System.currentTimeMillis() + String.format("%03d", random.nextInt(1000)))
                .transCode(prop.getTransCode());

        RequestContent.RequestBody requestBody = RequestContent.buildRequestBody().sendType(prop.getSendType())
                .smsType(prop.getSmsType())
                .messageInfoList(batchList);

        RequestContent content = new RequestContent(requestHeader, requestBody);
        String json = content.toString();

        MsgBodyVO bodyVO = new MsgBodyVO();
        bodyVO.setChannel(bodyVO.getChannel());
        AesCiphertext aes = new AesCiphertext(prop.getKey());
        bodyVO.setJson(aes.encryption(json));
        MD5Ciphertext md5 = new MD5Ciphertext();
        bodyVO.setSign(md5.encryption(prop.getSign()));
        bodyVO.setKey(1);
        //发送短信
        int flag = send(bodyVO);
        if (flag == 1) {
            //发送成功 修改状态
            msgs.stream().peek(msg -> msg.setDealTime(new Date())).forEach(msg -> this.useAlarmMsgDao.modifySent(msg));
        }

        System.out.println(bodyVO);


    }

    public int send(MsgBodyVO vo) {
        String str = JSONUtil.toJsonStr(vo);
        int flag = 0;
        try {

            PostMethod method = new PostMethod(prop.getUrl());
            StringRequestEntity entity = new StringRequestEntity(str, "application/json", "utf8");
            method.setRequestEntity(entity);
            HttpClient client = new HttpClient();
            client.executeMethod(method);
            logger.info("请求短信接口地址:{}", method.getURI());
            String body = method.getResponseBodyAsString();
            JSONObject json = JSONUtil.parseObj(body);
            JSONObject head = json.getJSONObject("head");
            Object respCode = head.get("respCode");
            if ("0000".equals(respCode)) {
                logger.info("发送成功");
                flag = 1;
            } else {
                logger.error("发送失败:错误码{},错误信息:{}", respCode, head.get("respMsg"));
            }

        } catch (IOException e) {
            e.printStackTrace();
            logger.error("发送失败:{}", e.getMessage());
        }
        return flag;
    }

}
